//
//  VIZCodeButton.m
//  WXMetro
//
//  Created by 位立志 on 17/2/19.
//  Copyright © 2017年 位立志. All rights reserved.
//

#import "VIZCodeButton.h"

@interface VIZCodeButton()

@property(nonatomic,strong)NSTimer *timer;

@end

@implementation VIZCodeButton


- (instancetype)init{
    
    if (self = [super init]) {
        self.layer.cornerRadius = kAutoWidth(5);
        self.layer.masksToBounds = YES;
        [self setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [self setTitleColor:[UIColor whiteColor] forState:UIControlStateDisabled];
        [self setTitle:@"  获取验证码  " forState:0];
                
        NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(runCode) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
        [timer setFireDate:[NSDate distantFuture]];
        self.timer = timer;
        
    }
    
    return self;

}

- (void)awakeFromNib{
    
    [super awakeFromNib];
    
//    self.layer.cornerRadius = 5*HEIGHT_RATIO;
//    self.layer.masksToBounds = YES;
    
    [self setTitle:@"  获取验证码  " forState:0];
    
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(runCode) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
    [timer setFireDate:[NSDate distantFuture]];
    self.timer = timer;
    
}

 
- (void)starteCode{
    //开始定时器
    [self.timer setFireDate:[NSDate distantPast]];
//    self.layer.borderColor = [kSecondTextColor CGColor];
    self.enabled = NO;
    self.backgroundColor = [UIColor lightGrayColor];
    if (self.runBgColor) {
        self.backgroundColor = self.runBgColor;
    }else{
        self.backgroundColor = kRGBA(245, 77, 83, 1);
    }
    if (self.runTextColor) {
        [self setTitleColor:self.runTextColor forState:UIControlStateDisabled];
    }else{
        [self setTitleColor:[UIColor whiteColor] forState:UIControlStateDisabled];
    }
    
}


- (void)runCode{
    
    if (self.seconds > -1) {
        [self setTitle:[NSString stringWithFormat:@"  %ld秒后重发  ",(long)self.seconds] forState:0];
        self.seconds--;
    }else{
        //关闭定时器
        [self.timer setFireDate:[NSDate distantFuture]];
        [self setTitle:@"  获取验证码  " forState:0];
        self.seconds = 60;
        if (self.willEndBlock) {            
            self.willEndBlock();
        }
    }
    
}


@end
